<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-10-25
 * @Time: 10:10
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： News.php
 */
namespace app\api\controller;

use app\api\model\special\SpecialColumn;
use app\api\model\Teacher;
use app\common\controller\Base;
use app\common\controller\SinaHq;
use app\common\model\ApiResponse;
use app\common\model\teacher\TeacherEssay;
use think\Cache;
use app\common\model\teacher\TeacherEssayCatalog;
use app\common\model\user\EssayCollection;
use app\common\model\user\EssayLiked;
use app\common\utils\DateTimeUtil;

use think\Db;
use think\Request;

class News extends Base {
    protected $news;
    protected $branches=[
        1=>['special_column_id'=>['<>',0],'teacher_id'=>['<>',0]],//掌乾观点
        2=>['special_column_id'=>0,'teacher_id'=>0] //财经资讯
    ];

    public function __construct(Request $request = null)
    {
        parent::__construct();

        $this->news = new \app\api\model\News();
    }

    /**
     * news_list
     * 资讯列表数据接口
     * @api http://xxx/api/web/news/list
     *
     * @author zhengkai
     * @date 2017-10-25
     * @version v1.1
     *
     * @return \think\response\Json
     */
    public function news_list()
    {
        return $this->news->query_news();
    }

    /**
     * 资讯列表
     *
     * @return ApiResponse
     */
    public function index() {
        $uid = checkUserToken();

        $form = $this->getAndCheckForm([
            ['page', '^\\d+$', ],
            ['rows', '^\\d+$', ],
            ['catalog_id', '^\\d+$',],
        ]);

        $catalog_id = intval($form['catalog_id'] ?? 0);
        $params = self::pageFormat($form);

        $re = TeacherEssay::apiList($params['limit'], $params['offset'], -1, '', $catalog_id, 0, $this->isPC(), $uid, 0);

        if ($this->isPC()) return ApiResponse::success($re['list'], $re['total'], $params['limit']);
        else return ApiResponse::success($re);
    }

    /**
     * 掌乾观点和财经资讯
     * @author wangxuejiao
     * @date 2018-04-20
     * @version pc
     *
     * @return ApiResponse
     *
     */
    public function viewpoint(){
        $form = $this->getAndCheckForm([
            ['page', 'integer', '参数类型不正确'],
            ['rows', 'integer', '参数类型不正确'],
            ['branch','integer|in:1,2,3'],
            ['catalog_id','integer','参数类型不正确'],
        ]);

        $form['branch']=$form['branch'] ?? 1;
        if(isset($form['catalog_id']) && $form['catalog_id']){
            $condition['catalog_id']=$form['catalog_id'];
        }else{
            $catalog=TeacherEssayCatalog::getChildIdByDesc('branch_'.$form['branch']);
            $condition['catalog_id']=empty($catalog) ? -1 : ['in',$catalog];
        }

        $condition['hide'] = 'false';

        if(isset($form['title']) && $form['title']){
            $condition['title']=['like','%'.$form['title'].'%'];
        }

        $form['page'] = $form['page'] ?? 1;
        $form['rows'] = $form['rows'] ?? 10;

        $data=TeacherEssay::getPagination($condition,$form['rows'],'id,cover,title,created,summary,special_column_id,catalog_id,teacher_id');

        foreach ($data['data'] as $k=>$v){
            $data['data'][$k]['cover']=$v['cover'] ? $v['cover'] : TeacherEssay::$DefaultCover;
            $data['data'][$k]['title']=htmlspecialchars_decode($v['title']);
            $data['data'][$k]['summary']=htmlspecialchars_decode($v['summary']);
            $data['data'][$k]['created']=date('Y-m-d H:i:s',strtotime($v['created']));
            $data['data'][$k]['created_at']=tranTime(strtotime($v['created']));
            if($form['branch']==1) $data['data'][$k]['is_special']=$v['special_column_id']>0 ? true : false;
            $data['data'][$k]['teacher_name']='';
            if($v['teacher_id']>0){
                $teacher=Teacher::getRealNameById($v['teacher_id']);
                $data['data'][$k]['teacher_name']=$teacher[0] ?? '';
            }
        }
        return ApiResponse::success($data);
    }

    /**
     * 财经资讯分类
     * @author wangxuejiao
     * @date 2018-04-20
     * @version pc
     *
     * @return ApiResponse
     *
     */
    public function catalog(){
        $form = $this->getAndCheckForm([
            ['branch','require|integer|in:1,2,3'],
        ]);
        $branch=TeacherEssayCatalog::findByDesc('branch_'.$form['branch'],'id');
        $catalog=TeacherEssayCatalog::findByParentId($branch['id'],'id,name,picture');
        foreach ($catalog as $k=>$v){
            $catalog[$k]['picture']=$v['picture']??TeacherEssayCatalog::defaultPicture();
        }
        return ApiResponse::success($catalog);
    }

    /**
     * getSubCatalog
     * 获取资讯子栏目
     *
     * @param int $cid 栏目id
     * @return array|mixed
     */
    public static function getSubCatalog($cid) {
        $data = Db::query("select * from teacher_essay_catalog where parent_id=:cid order by rank desc, id desc", ['cid'=>$cid]);
        $data = $data?:[];

        foreach ($data as &$val) {
            $val['picture'] = $val['picture']?:TeacherEssayCatalog::defaultPicture();
        }

        return $data;
    }

    /**
     * 文章详情
     * @author wangxuejiao
     * @date 2018-04-20
     * @version pc
     *
     * @return ApiResponse
     *
     */
    public function detail(){
        $uid = checkUserToken();
        $form = $this->getAndCheckForm([
            ['id','require|integer'],
        ]);
        $essay=TeacherEssay::getById($form['id'],$field='id,created,teacher_id,title,cover,content,summary,tags,attachment,catalog_id,bind_course');
        if(!$essay) return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'文章不存在');

        // zk 20180528 被绑定成为课程服务的文章检测课程是否已被购买
        $form['course_id'] = $form['course_id']??0;
        $bind_course = json_decode($essay['bind_course'],true);
        if (count($bind_course)) {
            if ((($essay['catalog_id']==config('course_serivce.internalReferenceId')) || ($essay['catalog_id']==config('course_serivce.researchReportId')))) {
                if ($form['course_id']>0) {
                    $isBuy = \app\api\model\TeacherEssay::checkBingCourseArticleIsBuy($uid, $form['id'], $form['course_id']);
                    if (!$isBuy) return ApiResponse::error(ApiResponse::ERR_NO_PURCHASE,'您还未购买该课程');
                } else {
                    return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'文章不存在');
                }
            }
        }
        unset($essay['bind_course']);

        $catalogs=TeacherEssayCatalog::getBrothersById($essay->catalog_id);
        $essay->next=$this->getNext(['catalog_id'=>empty($catalogs) ? -1 : ['in',$catalogs],'hide'=>'false','created'=>['<',$essay->created]]);
        $essay->created=date('Y-m-d H:i:s',strtotime($essay->created));
        $essay->cover = $essay->cover??TeacherEssay::$DefaultCover;
        $essay->tags = $essay->tags ? array_values(array_filter(explode(',',$essay->tags))) : [];
        if (isset($essay->attachment) && is_string($essay->attachment)) {
            $essay->attachment = json_decode($essay->attachment);
            $essay->attachment->has_video = isset($essay->attachment->video);
            $essay->attachment->has_audio = isset($essay->attachment->audio);
        }
        if (empty($essay->attachment)) {
            $essay->attachment = new \stdClass();
        }
        $essay->title = htmlspecialchars_decode($essay->title);
        $essay->summary = htmlspecialchars_decode($essay->summary);
        $essay->content = htmlspecialchars_decode($essay->content);

        $essay->like_num = EssayLiked::takeCount($essay->id);
        $essay->collection_num = EssayCollection::takeCount($essay->id);

        $essay->is_like = false;
        $essay->is_collection = false;
        if($uid>0){
            $essay->is_like=EssayLiked::is_exist($essay->id,$uid) ? true : false;
            $essay->is_collection=EssayCollection::is_exist($essay->id,$uid) ? true : false;
        }
        return ApiResponse::success($essay);
    }

    public function getNext(array $where){
        $data=TeacherEssay::getLimit($where,1,'id,title','created desc','',false);
        if(isset($data[0])){
            $next_essay=$data[0];
        }else{
            if(isset($where['created'][0])){
                $where['created'][0]=$where['created'][0]=='<' ? '>' : '<';
            }
            $data=TeacherEssay::getLimit($where,1,'id,title','created desc','',false);
            $next_essay=$data[0]??[];
        }
        if($next_essay){
            $next_essay['title']=mb_strlen($next_essay['title'])>10 ? mb_substr(htmlspecialchars_decode($next_essay['title']),0,10).'...' : $next_essay['title'];
        }else{
            $next_essay=new \stdClass();
        }
        return $next_essay;
    }

    /**
     * 相关新闻
     * @author wangxuejiao
     * @date 2018-04-23
     * @version pc
     *
     * @return ApiResponse
     */
    public function related(){
        $form = $this->getAndCheckForm([
            ['article_id','require|integer','参数类型不正确'],
            ['rows', 'integer', '参数类型不正确'],
        ]);

        $essay=TeacherEssay::getById($form['article_id'],$field='id,catalog_id');
        $condition['catalog_id']=$essay['catalog_id'];

        $condition['e.hide'] = 'false';

        $form['rows'] = $form['rows'] ?? 10;
        $data=TeacherEssay::getList($condition,$form['rows'],'e.id,e.title,e.created,e.catalog_id,e.teacher_id,t.realname,t.username');
        foreach ($data as $k=>$v){
            $data[$k]['created']=date('Y-m-d H:i:s',strtotime($v['created']));
            $data[$k]['created_time']=strtotime($v['created']);
        }
        return ApiResponse::success($data);
    }

    /**
     * pc_index_teacher_article
     * pc首页老师文章
     *
     * @author zhengkai
     * @date 2018-04-23
     *
     * @return array
     * @throws \think\exception\DbException
     */
    public static function pc_index_teacher_article()
    {
        $top = \app\api\model\TeacherEssay::getNewTeacherArticle(0, 1);
        $list = \app\api\model\TeacherEssay::getNewTeacherArticle(1, 4);
        $result = [
            'top' => $top[0],
            'list' => $list,
        ];

        return $result;
    }

    /**
     * pc_index_news
     * pc首页资讯文章
     *
     * @author zhengkai
     * @date 2018-04-23
     *
     * @return false|static[]
     */
    public static function pc_index_news()
    {
        $result = \app\api\model\TeacherEssay::getNewsArticle(0, 4);

        return $result;
    }

    /**
     * 收藏文章
     * @author wangxuejiao
     * @date 2018-04-24
     * @version pc
     *
     * @return ApiResponse
     */
    public function collection() {
        $uid = checkUserToken(true);
        $form = $this->getAndCheckForm([
            ['id', 'require|integer'],
            ['status', 'require|integer|in:1,2'],
        ]);
        $essay=TeacherEssay::getById($form['id'],'id');
        if(!$essay) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'文章不存在！');
        $exist=EssayCollection::is_exist($form['id'],$uid);
        if($form['status']==1){
            $res=!$exist ? EssayCollection::addOne($form['id'],$uid) : 1;
        }else{
            if(!$exist) return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'您还没有收藏该文章');
            $res=EssayCollection::remove($form['id'],$uid);
        }
        return $res ? ApiResponse::success($res) : ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED);

    }

    public function point(){
        $form = $this->getAndCheckForm([
            ['page', 'integer', '参数类型不正确'],
            ['rows', 'integer', '参数类型不正确'],
        ]);

        $catalog=TeacherEssayCatalog::getChildIdByDesc('branch_1');
        $condition['catalog_id']=empty($catalog) ? -1 : ['in',$catalog];

        $condition['te.hide'] = 'false';
        //modify cc 2018-10-17 去除观点的专栏文章
        $condition['te.special_column_id'] = 0;


        $form['page'] = $form['page'] ?? 1;
        $form['rows'] = $form['rows'] ?? 4;

        $data=TeacherEssay::getPointPagination($condition,$form['rows'],'te.id,cover,title,created,summary,special_column_id,stocks,teacher_id,realname as teacher_name,avatar as teacher_avatar,special_column_id');

        foreach ($data['data'] as $k=>$v){

            $data['data'][$k]['cover']=$v['cover'] ? $v['cover'] : TeacherEssay::$DefaultCover;
            $data['data'][$k]['title']=htmlspecialchars_decode($v['title']);
            $data['data'][$k]['summary']=htmlspecialchars_decode($v['summary']);
            $data['data'][$k]['created']=tranTime(strtotime($v['created']));
            $data['data'][$k]['teacher_name']=$v['teacher_name']??'';
            $data['data'][$k]['teacher_avatar']=$v['teacher_avatar']??'';

            $stocks_temp=json_decode($data['data'][$k]['stocks'],true);
            $stocks=[];
            if($stocks_temp){
                $stocks_info=SinaHq::getStock($stocks_temp);
                $stocks=SinaHq::changeData($stocks_info);
            }
            $data['data'][$k]['stocks']=$stocks;
            $data['data'][$k]['special_column_name']='';
            $data['data'][$k]['is_free']=1;
            if($v['teacher_id']>0 && $v['special_column_id']>0){
                $special_column=SpecialColumn::columns(['column_id'=>$v['special_column_id']],'column_id,column_title,column_price');
                if($special_column){
                    $data['data'][$k]['special_column_name']=$special_column['column_title'];
                    $data['data'][$k]['is_free']=$special_column['column_price']>0 ? 0 : 1;
                }
            }
        }

        return ApiResponse::success($data);
    }


    /**
     * 老师原创文章
     * @author wangxuejiao
     * @date 2018-05-25
     * @version pc
     *
     */
    public function originalArticle(){
        $form = $this->getAndCheckForm([
            ['page', 'integer', '参数类型不正确'],
            ['rows', 'integer', '参数类型不正确'],
        ]);
        $form['page'] = $form['page'] ?? 1;
        $form['rows'] = $form['rows'] ?? 10;

        $condition=['teacher_id'=>['>',0],'special_column_id'=>0,'catalog_id'=>['not in',[config('course_serivce.internalReferenceId'),config('course_serivce.researchReportId')]]];
        $data=TeacherEssay::getOriginalPagination($condition,$form['rows'],'te.id,te.cover,te.title,te.created,te.summary,t.realname as teacher_name');

        foreach ($data['data'] as $k=>$v){
            $data['data'][$k]['cover']=$v['cover'] ? $v['cover'] : TeacherEssay::$DefaultCover;
            $data['data'][$k]['title']=htmlspecialchars_decode($v['title']);
            $data['data'][$k]['summary']=htmlspecialchars_decode($v['summary']);
            $data['data'][$k]['created']=date('Y-m-d H:i:s',strtotime($v['created']));
            $data['data'][$k]['created_at']=tranTime(strtotime($v['created']));
        }
        return ApiResponse::success($data);
    }

    public function newsByCourse(){
        $form = $this->getAndCheckForm([
            ['page', 'integer', '参数类型不正确'],
            ['rows', 'integer', '参数类型不正确'],
            ['course_id','require|integer','参数类型不正确'],
            ['catalog_id','require|integer','参数类型不正确']
        ]);

        $condition['hide'] = 'false';

        $form['page'] = $form['page'] ?? 1;
        $form['rows'] = $form['rows'] ?? 10;

        $data=TeacherEssay::getPaginationByBindcourse($form['page'],$form['rows'],$form['course_id'],$form['catalog_id'],'id,cover,title,created,summary,special_column_id,catalog_id,teacher_id');

        foreach ($data['data'] as $k=>$v){
            $data['data'][$k]['cover']=$v['cover'] ? $v['cover'] : TeacherEssay::$DefaultCover;
            $data['data'][$k]['title']=htmlspecialchars_decode($v['title']);
            $data['data'][$k]['summary']=htmlspecialchars_decode($v['summary']);
            $data['data'][$k]['created']=date('Y-m-d H:i:s',strtotime($v['created']));
            $data['data'][$k]['created_at']=tranTime(strtotime($v['created']));
            $data['data'][$k]['teacher_name']='';
            if($v['teacher_id']>0){
                $teacher=Teacher::getRealNameById($v['teacher_id']);
                $data['data'][$k]['teacher_name']=$teacher[0] ?? '';
            }
        }
        return ApiResponse::success($data);
    }
}
